package org.adream.account.rest.api;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.adream.account.entity.RealNameAuthEntity;
import org.adream.account.entity.RealNameTmpEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.service.RealNameAuthService;
import org.adream.account.service.RealNameTmpService;
import org.adream.account.util.Constant;
import org.adream.account.util.FileUtils;
import org.adream.account.util.UserUtil;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

/**
 * "身份认证"实名信息 controller
 * @author sl
 *
 */
@RequestMapping("/realNameTmp")
@Controller
public class RealNameTmpApiController {

	private final static Logger logger = LoggerFactory.getLogger(RealNameTmpApiController.class);

	@Autowired
	private RealNameTmpService tmpService;
	
	@Autowired
	private RealNameAuthService authService;

	@Value("${image.file.path.verifypic}")
	private String verifyPicPath;

	/**
	 * 新增或更新
	 * 
	 * @param uid
	 * @param realNameTmpEntity
	 * @return
	 */
	@RequestMapping(value = "/{uid}", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> saveOrUpdateTmp(@PathVariable("uid") String uid, RealNameTmpEntity realNameTmpEntity,
			@RequestPart(value = "frontPic", required = false) MultipartFile frontPic,
			@RequestPart(value = "reversePic", required = false) MultipartFile reversePic, 
			HttpServletRequest request) {
		uid = (uid != null) ? uid : UserUtil.getUidByRequest(request);
		if (StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败,请求参数有误", null);
		}
		if (!StringUtils.isEmpty(frontPic) && frontPic.getSize() > Constant.ZERO) {
			String[] frontPicArray = Utils.dealPicFile(frontPic, verifyPicPath);
			if (frontPicArray.length == Constant.ONE) {
				realNameTmpEntity.setCreFrontPic(frontPicArray[0]);
			} else {
				realNameTmpEntity.setCreFrontPic(frontPicArray[1]);
				try {
					FileUtils.writeToFile(new File(frontPicArray[0] + frontPicArray[1]), frontPic.getInputStream());
				} catch (IOException e) {
					logger.info("正面证件照上传失败:)");
				}
			}
		}

		if (!StringUtils.isEmpty(reversePic) && reversePic.getSize() > Constant.ZERO) {
			String[] reversePicArray = Utils.dealPicFile(reversePic, verifyPicPath);
			if (reversePicArray.length == Constant.ONE) {
				realNameTmpEntity.setCreReversePic(reversePicArray[0]);
			} else {
				realNameTmpEntity.setCreReversePic(reversePicArray[1]);
				try {
					FileUtils.writeToFile(new File(reversePicArray[0] + reversePicArray[1]), reversePic.getInputStream());
				} catch (IOException e) {
					logger.info("反面证件照上传失败:)");
				}
			}
		}
		RealNameTmpEntity realNameTmp = tmpService.queryTmpByUid(uid);
		if (realNameTmp == null) {
			return tmpService.addRealNameTmp(realNameTmpEntity);
		}
		Utils.copyPropertiesIgnoreNull(realNameTmpEntity, realNameTmp);
		return tmpService.updateRealNameTmp(realNameTmp);
	}

	/**
	 * 不存在新增,存在更新（修改 只做护照提交）
	 * 
	 * @param uid
	 * @param realNameTmpEntity
	 * @return
	 */
	@RequestMapping(value = "/replaceTmp", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> replaceTmp(@RequestParam String p_realName,@RequestParam String p_creNum,
			@RequestPart(value = "p_frontPic", required = false) MultipartFile frontPic, 
			HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		String icon = request.getSession().getServletContext().getRealPath("/normal/images/tip.png");
		if (StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败,请求参数有误", null);
		}
		if(StringUtils.isEmpty(p_realName)||StringUtils.isEmpty(p_creNum)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "系统错误142,请联系管理员", null);
		}
		//数据长度校验
		if(p_realName != null && p_realName.length() > Constant.COMMON_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "真实姓名输入过长,请精简", null);
		}
		
		if(p_creNum != null && p_creNum.length() > Constant.COMMON_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "证件号输入太长,请精简", null);
		}
		RealNameTmpEntity realNameTmpEntity = new RealNameTmpEntity();
		realNameTmpEntity.setRealName(p_realName);
		realNameTmpEntity.setCreNum(p_creNum);
		realNameTmpEntity.setUid(uid);
		realNameTmpEntity.setCreType(Constant.ONE);
		realNameTmpEntity.setDr(Constant.ONE);
		if (!StringUtils.isEmpty(frontPic) && frontPic.getSize() > Constant.ZERO) {
			String[] frontPicArray = Utils.dealPicFile(frontPic, verifyPicPath);
			if (frontPicArray.length == Constant.ONE) {
				realNameTmpEntity.setCreFrontPic(frontPicArray[0]);
			} else {
				realNameTmpEntity.setCreFrontPic(Utils.otherPicExt2Jpg(frontPicArray[1]));
				try {
					boolean frontResult = Utils.compressAndAddWatermark(frontPic.getInputStream(), Constant.DEFAULT_COMPRESS_SCALE, icon, frontPicArray[0] + realNameTmpEntity.getCreFrontPic());
					if(!frontResult) {
						return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,图片上传失败", null);
					}
				} catch (IOException e) {
					logger.warn("正面证件照上传失败:)");
					return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,图片上传失败", null);
				}
			}
		}

	 
		RealNameTmpEntity realNameTmp = tmpService.queryTmpByUid(uid);
		if (realNameTmp == null) {
			//身份认证信息不存在,实名认证存在,实名认证creNum替换身份认证实名信息
			if(realNameTmpEntity.getCreNum() == null) {
				RealNameAuthEntity realNameAuth = authService.queryAuthByUid(realNameTmpEntity.getUid());
				if(realNameAuth != null) {
					realNameTmpEntity.setRealName(realNameAuth.getRealName());
					realNameTmpEntity.setCreType(realNameAuth.getCreType());
					realNameTmpEntity.setCreNum(realNameAuth.getCreNum());
				}
			}
			return tmpService.addRealNameTmp(realNameTmpEntity);
		}
		String oriCreNum = realNameTmp.getCreNum();
		
		//若前端提交的是之前存在的记录带*的creNum
		if(!StringUtils.isEmpty(realNameTmpEntity.getCreNum())
				&& realNameTmpEntity.getCreNum().indexOf("*") != -1) {
			//creType和creNum与之前提交的数据一致
			if(realNameTmpEntity.getCreType() == realNameTmp.getCreType() &&
					realNameTmpEntity.getCreNum().equals(Utils.replaceXing(realNameTmp.getCreNum(), 3, 4))) {
				realNameTmpEntity.setCreNum(oriCreNum);
			} else {
				logger.warn("更新失败,请求参数有误:(creType:" + realNameTmpEntity.getCreType() + ",creNum:" + realNameTmpEntity.getCreNum() + ")");
				return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请求参数有误", null);
			}
		}		
		Utils.copyPropertiesIgnoreNull(realNameTmpEntity, realNameTmp);
		//护照不需要背面照，以前如果身份认证有的 清空
		realNameTmp.setCreReversePic(null);
		return tmpService.updateRealNameTmp(realNameTmp);
	}

	/**
	 * 删除
	 * 
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/{uid}", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
	@ResponseBody
	public ResultModel<?> deleteRealNameTmp(@PathVariable("uid") String uid) {
		if (StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "删除失败,请求参数有误", null);
		}
		return tmpService.deleteRealNameTmp(uid);
	}

	/**
	 * 根据uid,删除标志查询
	 * 
	 * @param uid
	 * @param dr
	 * @return
	 */
	@RequestMapping(value = "/uid/{uid}/dr/{dr}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<RealNameTmpEntity> queryRealNameTmpByUidAndDr(@PathVariable("uid") String uid, @PathVariable("dr") Integer dr,
			HttpServletRequest request) {
		uid = (uid != null) ? uid : UserUtil.getUidByRequest(request);
		if (StringUtils.isEmpty(uid) || StringUtils.isEmpty(dr)) {
			return new ResultModel<RealNameTmpEntity>(ResultModel.ERR_PARAM, "查询失败,请求参数有误", null);
		}
		RealNameTmpEntity realNameTmp = tmpService.queryTmpByUidAndDr(uid, dr);
		if(realNameTmp == null) {
			return new ResultModel<RealNameTmpEntity>(ResultModel.NOT_FOUND_OBJECT, "查询失败,数据不存在", null);
		}
		return new ResultModel<RealNameTmpEntity>(ResultModel.SUCCESS, "查询成功", realNameTmp);
	}

	/**
	 * 根据删除标志,当前uid
	 * 
	 * @param dr
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/dr/{dr}/uid", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryRealNameTmpByCurUidAndDr(@PathVariable("dr") Integer dr, HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if (StringUtils.isEmpty(uid) || StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询失败,请求参数有误", null);
		}
		RealNameTmpEntity realNameTmp = tmpService.queryTmpByUidAndDr(uid, dr);
		if(realNameTmp == null) {				
			return new ResultModel<RealNameAuthEntity>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应数据", null);
		}
		realNameTmp.setCreNum(Utils.replaceXing(realNameTmp.getCreNum(), 3, 4));
		return new ResultModel<RealNameTmpEntity>(ResultModel.SUCCESS, "查询成功", realNameTmp);
	}

	/**
	 * 根据删除标志查询
	 * 
	 * @param dr
	 *            删除标志
	 * @return
	 */
	@RequestMapping(value = "/dr/{dr}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryRealNameTmpByDr(@PathVariable("dr") Integer dr) {
		if (StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询失败,请求参数有误", null);
		}
		List<RealNameTmpEntity> realNameTmps = tmpService.queryRealNameTmpsByDr(dr);
		if (realNameTmps == null || realNameTmps.size() == Constant.ZERO) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "查询失败,无相关数据", null);
		}
		return new ResultModel<List<RealNameTmpEntity>>(ResultModel.SUCCESS, "查询成功", realNameTmps);
	}
	/**
	 *  身份证  认证身份实名表
	 * 
	 * @param uid
	 * @param realNameTmpEntity
	 * @return
	 */
	@RequestMapping(value = "replaceIdCardTmp", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> replaceIdCardTmp(@RequestBody String jsonString,HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if (StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "系统错误336,请联系管理员", null);
		}
		if (StringUtils.isEmpty(jsonString)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "系统错误339,请联系管理员", null);
		}
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		RealNameTmpEntity realNameTmpEntity = (RealNameTmpEntity)JSONObject.toJavaObject(jsonObject, RealNameTmpEntity.class);
		if(realNameTmpEntity == null) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "系统错误344,请联系管理员", null);
		}
		if(realNameTmpEntity.getCreType()==null || realNameTmpEntity.getCreType() != 0) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "系统错误413,请联系管理员", null);
		}
		if(StringUtils.isEmpty(realNameTmpEntity.getCreFrontPic())
				||StringUtils.isEmpty(realNameTmpEntity.getCreReversePic())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "系统错误417,请联系管理员", null);
		}
		//数据长度校验
		if(realNameTmpEntity.getRealName() != null && realNameTmpEntity.getRealName().length() > Constant.COMMON_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "真实姓名输入过长,请精简", null);
		}
		
		if(realNameTmpEntity.getCreNum() != null && realNameTmpEntity.getRealName().length() > Constant.COMMON_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "证件号输入太长,请精简", null);
		}
		
		realNameTmpEntity.setUid(uid);
		realNameTmpEntity.setDr(Constant.ONE);
 
		RealNameTmpEntity realNameTmp = tmpService.queryTmpByUid(uid);
		if (realNameTmp == null) {
			//身份认证信息不存在,实名认证存在,实名认证creNum替换身份认证实名信息
			if(realNameTmpEntity.getCreNum() == null) {
				RealNameAuthEntity realNameAuth = authService.queryAuthByUid(realNameTmpEntity.getUid());
				if(realNameAuth != null) {
					realNameTmpEntity.setRealName(realNameAuth.getRealName());
					realNameTmpEntity.setCreType(realNameAuth.getCreType());
					realNameTmpEntity.setCreNum(realNameAuth.getCreNum());
				}
			}
			return tmpService.addRealNameTmp(realNameTmpEntity);
		}
		String oriCreNum = realNameTmp.getCreNum();
		
		//若前端提交的是之前存在的记录带*的creNum
		if(!StringUtils.isEmpty(realNameTmpEntity.getCreNum())
				&& realNameTmpEntity.getCreNum().indexOf("*") != -1) {
			//creType和creNum与之前提交的数据一致
			if(realNameTmpEntity.getCreType() == realNameTmp.getCreType() &&
					realNameTmpEntity.getCreNum().equals(Utils.replaceXing(realNameTmp.getCreNum(), 3, 4))) {
				realNameTmpEntity.setCreNum(oriCreNum);
			} else {
				logger.warn("更新失败,请求参数有误:(creType:" + realNameTmpEntity.getCreType() + ",creNum:" + realNameTmpEntity.getCreNum() + ")");
				return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请求参数有误", null);
			}
		}		
		Utils.copyPropertiesIgnoreNull(realNameTmpEntity, realNameTmp);
		return tmpService.updateRealNameTmp(realNameTmp);
	}
	
	//
	/**
	 * 其他类型认证
	 * @param p_realName
	 * @param p_creNum
	 * @param frontPic
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/replaceOtherTmp", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> replaceOtherTmp(@RequestParam String o_realName,@RequestParam String o_creNum,
			@RequestPart(value = "o_frontPic", required = false) MultipartFile frontPic, 
			HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		String icon = request.getSession().getServletContext().getRealPath("/normal/images/tip.png");
		if (StringUtils.isEmpty(uid)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败,请求参数有误", null);
		}
		if(StringUtils.isEmpty(o_realName)||StringUtils.isEmpty(o_creNum)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "系统错误,请联系管理员", null);
		}
		//数据长度校验
		if(o_realName != null && o_realName.length() > Constant.COMMON_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "真实姓名输入过长,请精简", null);
		}
		
		if(o_creNum != null && o_creNum.length() > Constant.COMMON_DATA_LENGTH) {
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "证件号输入太长,请精简", null);
		}
		RealNameTmpEntity realNameTmpEntity = new RealNameTmpEntity();
		realNameTmpEntity.setRealName(o_realName);
		realNameTmpEntity.setCreNum(o_creNum);
		realNameTmpEntity.setUid(uid);
		realNameTmpEntity.setCreType(Constant.TWO);
		realNameTmpEntity.setDr(Constant.ONE);
		if (!StringUtils.isEmpty(frontPic) && frontPic.getSize() > Constant.ZERO) {
			//String[] frontPicArray = Utils.dealPicFile(frontPic, verifyPicPath);
				String[] frontPicArray = Utils.getFileName(frontPic, verifyPicPath);
				realNameTmpEntity.setCreFrontPic(Utils.otherPicExt2Jpg(frontPicArray[1]));
				try {
					boolean frontResult = Utils.compressAndAddWatermark(frontPic.getInputStream(), Constant.DEFAULT_COMPRESS_SCALE, icon, frontPicArray[0] + realNameTmpEntity.getCreFrontPic());
					if(!frontResult) {
						return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,图片上传失败", null);
					}
				} catch (IOException e) {
					logger.warn("图片上传失败:)");
					return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,图片上传失败", null);
				}
		}

	 
		RealNameTmpEntity realNameTmp = tmpService.queryTmpByUid(uid);;
		if (realNameTmp == null) {
			//身份认证信息不存在,实名认证存在,实名认证creNum替换身份认证实名信息
			if(realNameTmpEntity.getCreNum() == null) {
				RealNameAuthEntity realNameAuth = authService.queryAuthByUid(realNameTmpEntity.getUid());
				if(realNameAuth != null) {
					realNameTmpEntity.setRealName(realNameAuth.getRealName());
					realNameTmpEntity.setCreType(realNameAuth.getCreType());
					realNameTmpEntity.setCreNum(realNameAuth.getCreNum());
				}
			}
			return tmpService.addRealNameTmp(realNameTmpEntity);
		}
		String oriCreNum = realNameTmp.getCreNum();
		
		//若前端提交的是之前存在的记录带*的creNum
		if(!StringUtils.isEmpty(realNameTmpEntity.getCreNum())
				&& realNameTmpEntity.getCreNum().indexOf("*") != -1) {
			//creType和creNum与之前提交的数据一致
			if(realNameTmpEntity.getCreType() == realNameTmp.getCreType() &&
					realNameTmpEntity.getCreNum().equals(Utils.replaceXing(realNameTmp.getCreNum(), 3, 4))) {
				realNameTmpEntity.setCreNum(oriCreNum);
			} else {
				logger.warn("更新失败,请求参数有误:(creType:" + realNameTmpEntity.getCreType() + ",creNum:" + realNameTmpEntity.getCreNum() + ")");
				return new ResultModel<String>(ResultModel.ERR_PARAM, "更新失败,请求参数有误", null);
			}
		}		
		Utils.copyPropertiesIgnoreNull(realNameTmpEntity, realNameTmp);
		//护照不需要背面照，以前如果身份认证有的 清空
		realNameTmp.setCreReversePic(null);
		return tmpService.updateRealNameTmp(realNameTmp);
	}
}